#include "mainwindow.h"
#include <QDebug>
#include <QThread>
#include <QTimer>
using namespace cv;
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    isWork = 0;
    camera = cvCreateCameraCapture(CV_CAP_V4L2);
    src = cvCreateImage(cvSize(480, 480), 8, 3);
    Icr = cvCreateImage(cvSize(480, 480), 8, 1);
    if(!camera)return;
    QTimer *timer= new QTimer();
    QHBoxLayout *hbox = new QHBoxLayout();
    btn = new QPushButton("开始");
    label = new QLabel("值");
    hbox->addWidget(label);
    hbox->addWidget(btn);
    QWidget *widget = new QWidget();
    widget->setLayout(hbox);
    this->setCentralWidget(widget);
    connect(btn, SIGNAL(clicked()), this, SLOT(changeWorkState()));
    connect(timer, SIGNAL(timeout()), this, SLOT(work()));
    timer->start(20);
    this->show();
    //work();
}


MainWindow::~MainWindow()
{
    isWork = -1;
    cvReleaseCapture(&camera);
    cvReleaseImage(&src);
    cvReleaseImage(&Icr);
}

void MainWindow::changeWorkState()
{
    isWork ^= 1;
    if(isWork){
        btn->setText("关闭");
    }
    else btn->setText("开始");
}
QString Dir[5] = {"左", "下", "上", "右", "中"};
void MainWindow::work()
{
    if(isWork == 1)
    {

        I = cvQueryFrame(camera);
        if(!I) return;
        cvResize(I, src);
        otsu(src, Icr);
        //qDebug()<< findContours(Icr);
        CvPoint point = det.Detect(Icr, Icr);
        if(point.x == -1) return;
        label->setText(Dir[detectCode(point, Icr->width, Icr->height)]);
    }
}
